import { Request, Response, NextFunction } from 'express';
import { RegisterDTO, LoginDTO } from '../dto/user.dto';
import * as authService from '../services/auth.service';
import { signToken } from '../utils/jwt';

export const register = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const input = RegisterDTO.parse(req.body);
    const user = await authService.register(input);
    res.safeJson({
      id: user.id,
      username: user.username,
      email: user.email,
      phone: user.phone,
      avatar: user.avatar,
      bio: user.bio
    }, '注册成功', 0, 200);
  } catch (err) {
    next(err);
  }
};

export const login = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const input = LoginDTO.parse(req.body);
    const user = await authService.login(input);
    const token = signToken({ id: user.id, username: user.username });
    res.safeJson({ token }, '登录成功');
  } catch (err) {
    next(err);
  }
};
